# -*- coding: utf-8 -*-
import traceback
import requests
import json
import logging

from app.db.crud import get_posts_with_source_sql
from app.db.database import SessionLocal
from app.dify.llm_with_jina import LLMWithJina
from app.dify.llm_without_jina import LLMWithOutJina
from sqlalchemy import update
from app.db.models import TPost
from app.myttl.tts_automation import TTSAutomation, Article
from app.monitor import status_manager

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class JudgeWorker:
    def __init__(self):
        # 首先获取最近24小时没评分的文章数据,并且包含类型信息,然后进行循环根据类型调用llm类进行分数的保存,并打印结果
        self.name = ''
        self.crawl_api_url = 'http://47.99.144.80:6664/api/crawl'
        self.headers = {
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'Content-Type': 'application/json',
            'Accept': '*/*',
            'Connection': 'keep-alive'
        }

    def get_article_content(self, url):
        try:
            payload = {"url": url}
            response = requests.post(self.crawl_api_url, headers=self.headers, json=payload)
            response.raise_for_status()  # 检查响应状态
            return response.json()
        except Exception as e:
            logger.error(f"Error fetching article content for URL {url}: {str(e)}")
            error_msg = f"Error fetching article content for URL {url}: {str(e)}"
            status_manager.record_error('content_fetch', error_msg)
            return None

    def update_post_data(self, db, post_id, article_data):
        try:
            # 将整个返回数据转换为JSON字符串
            content_json = json.dumps(article_data, ensure_ascii=False)
            
            # 更新到content字段
            stmt = update(TPost).where(TPost.id == post_id).values(content=content_json)
            db.execute(stmt)
            db.commit()
            status_manager.increment_count('content_fetch')
            return True
        except Exception as e:
            logger.error(f"Error updating content for post {post_id}: {str(e)}")
            error_msg = f"Error updating content for post {post_id}: {str(e)}"
            status_manager.record_error('content_fetch', error_msg)
            db.rollback()
            return False

    def run(self):
        with SessionLocal() as db:
            posts = get_posts_with_source_sql(db, None)
            articles_for_tts = []
            for post in posts:
                try:
                    # 如果来源是这些平台，则跳过llm判断和生成音频
                    if post.source_name in ['bilibili','douyin','baidu','tieba','xueqiu','toutiao','bilibili-hot-search', 'xueqiu-hotstock', 'weibo']:
                        continue
                    else:
                        # 先获取文章内容
                        article_content = self.get_article_content(post.url)
                        if article_content is None:
                            logger.warning(f"Skipping post {post.post_id} due to content fetch failure")
                            continue
                        
                        # 更新文章数据到数据库的content字段
                        if self.update_post_data(db, post.post_id, article_content):
                            logger.info(f"Successfully updated content for post {post.post_id}")
                        else:
                            logger.error(f"Failed to update content for post {post.post_id}")
                            continue
                            
                        # llm判断和生成音频
                        if article_content['markdown'] is not None:
                            #如果内容大于5000字，则截取
                            if len(article_content['markdown']) > 5000:
                                article_content['markdown'] = article_content['markdown'][:4500]
                            llm_with_jina = LLMWithOutJina(post.post_id, article_content['markdown'], post.url)
                            success = llm_with_jina.run_workflow()
                            if success:
                                status_manager.increment_count('llm_judge')
                            logger.info(f'title: {post.title}, Success: {success}')
                            article = Article(id=post.post_id, content=article_content['markdown'])
                            articles_for_tts.append(article)
                        else:
                            logger.error(f"Failed to update content for post has no markdown {post.post_id}")
                            continue
                except Exception as e:
                        # 打印错误信息
                    logger.error(f"Error processing post {post.post_id} (Title: {post.title}):")
                    logger.error(f"Exception: {e}")
                    logger.error("Traceback:")
                    logger.error(traceback.format_exc())
                    continue

            
if __name__ == '__main__':
    worker = JudgeWorker()
    worker.run()
